package com.lson.zuul.route;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.lson.common.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

@Slf4j
@Component
public class ClientRoute implements FallbackProvider {
    @Override
    public String getRoute() {
        return "erueka-client";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        ClientHttpResponse clientHttpResponse = new ClientHttpResponse() {
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mediaType = new MediaType("application","json", Charset.forName("UTF-8"));
                httpHeaders.setContentType(mediaType);
                return httpHeaders;
            }

            @Override
            public InputStream getBody() throws IOException {
                ResultMsg fail = ResultMsg.fail(getRoute() + "服务不可用");
                return new ByteArrayInputStream(JSON.toJSONString(fail).getBytes());
            }

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return  HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return  this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }
        };
        return clientHttpResponse;
    }
}
